import { useRef, useState } from 'react'
/**
 * 如果你的组件需要存储一些值，但不影响渲染逻辑，请选择 ref。 ref 最常见的用法是访问 DOM 元素
 * 不要在render 期间 读取ref.current
 * 1 存储 timeout ID
 * 2 存储和操作 DOM 元素
 * 3 存储不需要被用来计算 JSX 的其他对象。
 * @returns
 */
const Stopwatch = () => {
  const [startTime, setStartTime] = useState(null)
  const [now, setNow] = useState(null)
  const intervalRef = useRef(null)
  const handleStart = () => {
    const nowMills = Date.now()
    setNow(nowMills)
    setStartTime(nowMills)
    clearInterval(intervalRef.current)
    intervalRef.current = setInterval(() => {
      setNow(Date.now)
    }, 10)
  }
  const handleStop = () => {
    clearInterval(intervalRef.current)
  }
  let secondsPassed = 0
  if (startTime && now) {
    secondsPassed = (now - startTime) / 1000
  }
  return (
    <>
      <h1>时间过去了： {secondsPassed.toFixed(3)}</h1>
      <button onClick={handleStart}>开始</button>
      <button onClick={handleStop}>停止</button>
    </>
  )
}

// let timeout = null
function DebouncedButton({ onClick, children }) {
  const timeoutRef = useRef(null)
  return (
    <button
      onClick={() => {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = setTimeout(() => {
          onClick()
        }, 1000)
      }}
    >
      {children}
    </button>
  )
}
function Dashboard() {
  return (
    <>
      {/**
       * 每个DebouncedButton的timeoutRef都是独立的，互相不影响的
       */}
      <DebouncedButton onClick={() => alert('宇宙飞船已发射！')}>发射宇宙飞船</DebouncedButton>
      <DebouncedButton onClick={() => alert('汤煮好了！')}>煮点儿汤</DebouncedButton>
      <DebouncedButton onClick={() => alert('摇篮曲唱完了！')}>唱首摇篮曲</DebouncedButton>
    </>
  )
}

export default function App() {
  const numRef = useRef(0)
  function handleClick() {
    numRef.current++ // 组件不会在每次递增时重新渲染
  }

  return (
    <div>
      {numRef.current}
      <button onClick={handleClick}>点击我！</button>
      <Stopwatch />
      <Dashboard />
    </div>
  )
}
